package com.sweets.look.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebIconDatabase;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewDatabase;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Pattern;

import com.sweets.look.R;
import com.sweets.look.constant.Constants;
import com.sweets.look.database.DatabaseHandler;
import com.sweets.look.database.DownloadHandler;
import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.ui.activity.BrowserActivity;
import com.sweets.look.ui.widget.MarkEditDialog;
import com.sweets.look.ui.widget.MarkEditDialog.OnCustomDialogListener;

public final class BrowserUtils {
    private static final String TAG = BrowserUtils.class.getSimpleName();

    public static Bitmap captureAll(View view, float width, float height, boolean scroll, Bitmap.Config
            config) {
        if (!view.isDrawingCacheEnabled()) {
            view.setDrawingCacheEnabled(true);
        }

        Bitmap v6 = Bitmap.createBitmap(((int) width), ((int) height), config);
        v6.eraseColor(-1);
        Canvas v0 = new Canvas(v6);
        int v7 = view.getLeft();
        int v10 = view.getTop();
        if (scroll) {
            v7 = view.getScrollX();
            v10 = view.getScrollY();
        }

        int v9 = v0.save();
        v0.translate(((float) (-v7)), ((float) (-v10)));
        float v8 = width / (((float) view.getWidth()));
        v0.scale(v8, v8, ((float) v7), ((float) v10));
        view.draw(v0);
        v0.restoreToCount(v9);
        Paint v5 = new Paint();
        v5.setColor(0);
        v0.drawRect(0f, 0f, 1f, height, v5);
        v0.drawRect(width - 1f, 0f, width, height, v5);
        v0.drawRect(0f, 0f, width, 1f, v5);
        v0.drawRect(0f, height - 1f, width, height, v5);
        v0.setBitmap(null);
        return v6;
    }

    /**
     * 截取webView可视区域的截图
     *
     * @param view 前提：WebView要设置webView.setDrawingCacheEnabled(true);
     * @return
     */
    public static Bitmap captureVisible(View view) {
        return view.getDrawingCache();
    }

    public static String changeLink(String url) {
        if (url != null && ((getDomainName(url).equalsIgnoreCase("m.baidu.com"))
                || (getDomainName(url).equalsIgnoreCase("www.baidu.com")))) {

            if (url.substring(url.indexOf("baidu.com") + 9).equals("/")) {
                url = url + "?from=" + Constants.BAIDU_LINK;
            } else if (url.substring(url.indexOf("baidu.com") + 9).equals("")) {
                url = url + "/?from=" + Constants.BAIDU_LINK;
            }
        }

        return url;
    }

    public static void clearWebStorage() {
        WebStorage.getInstance().deleteAllData();
    }

    public static void clearWebViewCache(Context context) {
        WebView webView = new WebView(context);
        webView.clearCache(true);
        webView.destroy();
    }

    /**
     * 清除cookie
     *
     * @param context
     */
    public static void clearWebViewCookies(Context context) {
        WebViewDatabase database = WebViewDatabase.getInstance(context);
        database.clearFormData();
        database.clearHttpAuthUsernamePassword();
        if (Build.VERSION.SDK_INT < 18) {
            database.clearUsernamePassword();
        }

        CookieSyncManager.createInstance(context);
        CookieManager.getInstance().removeAllCookie();
    }

    public static void clearWebViewFormData(Context context) {
        WebViewDatabase.getInstance(context).clearFormData();
    }

    /**
     * 清掉历史记录
     *
     * @param context
     */
    public static void clearWebViewHistory(Context context) {
        DatabaseHandler handler = new DatabaseHandler(context);
        handler.deleteAllHistoryItems();
        handler.close();
        if (Constants.API < 18) {
            WebIconDatabase.getInstance().removeAllIcons();
        }

        trimCache(context);
    }

    public static void copy(Context context, String url) {
        if (url != null) {
            ((ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText(null, url.trim()));
        }
    }

    public static void copyText(Context context, String url) {
        BrowserUtils.copy(context, url);
        ViewUtils.showToast(context.getResources().getString(R.string.toast_copy_text_successful), context);
    }

    public static void copyURL(Context context, String url) {
        copy(context, url);
        ViewUtils.showToast(context.getResources().getString(R.string.toast_copy_url_successful), context);
    }

    /**
     * 下载文件
     *
     * @param activity
     * @param url                下载地址
     * @param userAgent
     * @param contentDisposition
     * @param mimeType           文件类型
     * @param privateBrowsing
     * @param fileName
     * @param withDialog
     */
    public static void downloadFile(final Activity activity, final String url, final String userAgent, final String contentDisposition,
                                    final String mimeType, final boolean privateBrowsing, String fileName, boolean withDialog) {
        LogUtils.d(TAG, "try to download file");

        PreferenceManager preferenceManager = PreferenceManager.getInstance();
        //检查插件,优先adm下载
//        if ((Utils.checkAddon(activity, "com.dv.adm.pay")) && (preferenceManager.getAddonsEnabled("com.dv.adm.pay"))) {
//            LogUtils.d(TAG, "try to use adm");
//            try {
//                Intent intent = new Intent();
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//268435456
//                intent.setType("text/plain");
//                intent.putExtra("android.intent.extra.TEXT", url);
//                intent.setComponent(new ComponentName("com.dv.adm.pay", "com.dv.adm.pay.AEditor"));
//                activity.startActivity(intent);
//                return;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

        LogUtils.d(TAG, "try to use system download manager");
        if (fileName == null) {
            int v8 = url.lastIndexOf(63);
            int v9 = url.lastIndexOf(47);
            fileName = v8 != -1 && v9 != -1 && v8 > v9 + 1 ? url.substring(v9 + 1, v8) : v9 != -1 ?
                    url.substring(url.lastIndexOf(47) + 1) : UUID.randomUUID() + ".jpg";
            if (fileName.endsWith(".bin")) {
                fileName = fileName.replace(".bin", ".png");
            }
        }

        if (withDialog) {//需不需要弹个提示框
            new MarkEditDialog(activity).builder()
                    .setTitle(activity.getResources().getString(R.string.dialog_download))
                    .setCanceledOnTouchOutside(false)
                    .setTitleHint("", fileName).setMsgHint("", url)
                    .setOperateButton(R.drawable.menu_share, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            IntentUtils.share(activity, url);
                        }
                    }).setPositiveButton(activity.getResources().getString(R.string.action_ok),
                    new OnCustomDialogListener() {
                        @Override
                        public void back(String title, String msg, String other) {
                            //开始下载
                            DownloadHandler.onDownloadStart(activity, url, userAgent,
                                    contentDisposition, mimeType, privateBrowsing, title);
                        }
                    }).setNegativeButton(activity.getResources().getString(R.string.action_cancel), null)
                    .show();
        } else {//开始下载
            DownloadHandler.onDownloadStart(activity, url, userAgent,
                    contentDisposition, mimeType, privateBrowsing, fileName);
        }
    }

    /**
     * 修正url
     *
     * @param url
     * @return
     */
    public static String fixUrl(String url) {
        if (url == null) {
            return "";
        }

        if (!url.startsWith("javascript:")) {
            url = Pattern.compile("\\s*|\t|\r|\n").matcher(url).replaceAll("");
        }

        if (!url.startsWith("about:") && !url.startsWith("javascript:") && !url.contains("://")) {
            url = "http://" + url;
        }

        return url;
    }

    /**
     * @param url
     * @return
     */
    public static String getDomainName(String url) {

        if (url.indexOf(47, 8) != -1) {
            url = url.substring(0, url.indexOf(47, 8));
        }

        if (url.contains("://")) {
            url = url.substring(url.indexOf("://") + 3);
        }

        return url;
    }

    /**
     * 获得真是域名
     *
     * @param url
     * @return
     */
    public static String getRealDomainName(String url) {

        if (url.indexOf(47, 8) != -1) {
            url = url.substring(0, url.indexOf(47, 8));
        }

        if (url.lastIndexOf(".") != -1 && url.lastIndexOf(".") != url.indexOf(".")) {
            String[] v0 = url.split("\\.");
            url = v0[v0.length - 2] + "." + v0[v0.length - 1];
        }

        if (url.contains("://")) {
            url = url.substring(url.indexOf("://") + 3);
        }

        return url;
    }

    /**
     * 安装插件
     *
     * @param activity
     * @param packageName
     */
    public static void installAddon(Activity activity, String packageName) {

        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setComponent(null);
        if (Build.VERSION.SDK_INT >= 15) {
            intent.setSelector(null);
        }
        intent.setData(Uri.parse("market://details?id=" + packageName));
        try {
            activity.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            activity.startActivity(new Intent("android.intent.action.VIEW",
                    Uri.parse("http://m.coolapk.com/apk/" + packageName),
                    activity, BrowserActivity.class));
        }
    }

    /**
     * 是不是标签页
     *
     * @param context
     * @param url
     * @return
     */
    public static boolean isBookmarkPage(Context context, String url) {

        String bookmarks = "file://" + context.getFilesDir().getPath() + "/bookmarks.html";
        String folder = "file://" + context.getFilesDir().getPath() + "/folder.html";
        if (url != null) {
            if (!url.equals(bookmarks) && !url.equals(folder)) {
                return false;
            }
            return true;
        }
        return false;

    }

    /**
     * GPRS是否链接了
     *
     * @param context
     * @return
     */
    public static boolean isDataConnected(Context context) {
        boolean isDataConnected = false;
        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getNetworkInfo(0);
        if (networkInfo != null && (networkInfo.isConnected())) {
            isDataConnected = true;
        }

        return isDataConnected;
    }

    public static boolean isDefaultHomePage(Context context, String url) {
        String homepage = "file://" + context.getFilesDir().getPath() + "/homepage.html";
        return !(url == null || !url.equals(homepage));
    }

    public static boolean isHistoryPage(Context context, String url) {
        String history = "file://" + context.getFilesDir().getPath() + "/history.html";
        return !(url == null || !url.equals(history));
    }

    /**
     * 是否是本地页面
     *
     * @param url
     * @return
     */
    public static boolean isLocalPage(String url) {
        if (url != null) {
            if (!url.startsWith("file://")) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * @param context
     * @param url
     * @return
     */
    public static boolean isSetedHomePage(Context context, String url) {
        if (url != null) {
            String homepage = PreferenceManager.getInstance().getHomepage();
            if (homepage != null) {
                String v2;
                if ((homepage.startsWith("about:home")) || (homepage.startsWith("about:links"))) {
                    v2 = "file://" + context.getFilesDir().getPath() + "/homepage.html";
                } else if (homepage.startsWith("about:bookmarks")) {
                    v2 = "file://" + context.getFilesDir().getPath() + "/bookmarks.html";
                } else {
                    v2 = homepage;
                }

                if (!url.equalsIgnoreCase(v2) && !url.equalsIgnoreCase(v2 + "/")) {
                    return false;
                }

                return true;
            }
        }

        return false;
    }

    /**
     * URL是否合法
     *
     * @param url
     * @return
     */
    public static boolean isURL(String url) {
        if (url == null) {
            return false;
        }

        url = url.trim().toLowerCase(Locale.getDefault());
        if (url.startsWith(Constants.URL_SCHEME_ABOUT)) {
            return true;
        }
        if (url.startsWith(Constants.URL_SCHEME_MAIL_TO)) {
            return true;
        }
        if (url.startsWith(Constants.URL_SCHEME_FILE)) {
            return true;
        }
        if (url.startsWith(Constants.URL_SCHEME_JS)) {
            return true;
        }
        if (url.startsWith(Constants.URL_SCHEME_HTTP)) {
            return true;
        }
        if (url.startsWith(Constants.URL_SCHEME_HTTPS)) {
            return true;
        }
        if (url.startsWith(Constants.URL_SCHEME_FTP)) {
            return true;
        }
        if (url.startsWith(Constants.URL_SCHEME_INTENT)) {
            return true;
        }

        if (url.contains("://")) {
            return true;
        }

        return Pattern.compile("^((ftp|http|https|intent)?://)?(([0-9a-z_!~*\'().&=+$%-]+: )?[0-9a-z_!~*\'().&=+$%-]+@)?(([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-z_!~*\'()-]+\\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!~*\'().;?:@&=+$,%#-]+)+/?)$")
                .matcher(url).matches();
    }

    /**
     * webview是否有
     *
     * @param context
     * @return
     */
    public static boolean isWebViewInstalled(Context context) {
        boolean isInstalled = false;
        if (Build.VERSION.SDK_INT >= 21) {
            PackageInfo packageInfo;
            try {
                packageInfo = context.getPackageManager().getPackageInfo("com.google.android.webview", 0);
            } catch (PackageManager.NameNotFoundException e) {
                packageInfo = null;
            }

            if (packageInfo != null) {
                return true;
            }
        } else {
            isInstalled = true;
        }

        return isInstalled;
    }

    /**
     * wifi是否链接
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        boolean isConnect = true;
        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
                .getNetworkInfo(1);//1
        if (networkInfo == null || !networkInfo.isConnected()) {
            isConnect = false;
        }

        return isConnect;
    }

    /**
     * 扫描二维码
     *
     * @param activity
     */
    public static void scanQrCode(Activity activity) {
        Intent intent = new Intent();
        intent.setClassName("com.sweets.look", "com.candy.scanner.CaptureActivity");
        try {
            activity.startActivityForResult(intent, 9999);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 截屏保存
     *
     * @param context
     * @param bitmap
     * @param name
     * @return
     */
    public static String screenshot(Context context, Bitmap bitmap, String name) {
        if (bitmap != null) {
            File fileDir = new File(Utils.getDownloadPath() + "screenshots/");
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }

            File pngFile = new File(fileDir, name.trim() + "-" + String.valueOf(System.currentTimeMillis()) + ".png");
            try {
                FileOutputStream out = new FileOutputStream(pngFile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
                context.sendBroadcast(new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE", Uri
                        .fromFile(pngFile)));
                return pngFile.getAbsolutePath();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 删缓存目录
     *
     * @param context
     */
    private static void trimCache(Context context) {
        try {
            File file = context.getCacheDir();
            if (file == null) {
                return;
            }
            if (!file.isDirectory()) {//不是目录
                return;
            }
            FileUtils.deleteDir(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void updateWebView(Activity activity) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setComponent(null);
        if (Build.VERSION.SDK_INT >= 15) {
            intent.setSelector(null);
        }

        intent.setData(Uri.parse("market://details?id=com.google.android.webview"));
        try {
            activity.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

}

